package org.hepeng.workx.exception.translate;

import org.hepeng.workx.extension.XLoader;
import org.hepeng.workx.util.proxy.Invocation;
import org.hepeng.workx.util.proxy.Invoker;
import org.hepeng.workx.util.proxy.ProxyFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.LinkedList;
import java.util.List;

/**
 * @author he peng
 */
public class ExceptionTranslateAnnotationBeanPostProcessor implements BeanPostProcessor , ApplicationContextAware {

    private ProxyFactory proxyFactory = XLoader.getXLoader(ProxyFactory.class).getX();

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        ExceptionTranslateMethodResolver translateMethodResolver =
                new ExceptionTranslateMethodResolver(bean.getClass(), this.context);
        if (translateMethodResolver.hasTranslator()) {
            ExceptionTranslatorInvoker translatorInvoker = new ExceptionTranslatorInvoker(bean , translateMethodResolver);
            List<Invoker> invokers = new LinkedList<>();
            invokers.add(translatorInvoker);
            Object proxy = proxyFactory.createProxy(bean , null , invokers , null);
            return proxy;
        }

        return bean;
    }
}
